package com.atguigu.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Objects;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/**
 * @author 望轩
 * @createDate 2024/8/22 17:55
 * Gateway网关路由配置可以写在配置文件中，也可以直接通过类来配置
 */
@Component
@Slf4j
public class TestRouterFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        //这里只对/payment_api/test请求路径进行路由转发，如果路径里面不包含test，则不再进行Gateway路由转发到别的微服务
        if (!path.contains("/test")) {
            return chain.filter(exchange);
        }
        // 取出当前的route对象，重新设置Route地址
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        Route newRoute = Route.async().asyncPredicate(Objects.requireNonNull(route).getPredicate())
                .filters(route.getFilters())
                .id("payment-order")
                .order(route.getOrder())
                .uri("lb://CLOUD-PAYMENT-SERVICE/payment_api/test")
                .build();
        exchange.getAttributes().put(GATEWAY_ROUTE_ATTR, newRoute);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}